<?php

class CieloRequest extends TXObject {
	
	public $serviceUrl = 'https://comercio.locaweb.com.br/comercio.comp';
	
	protected $options = array();
	protected $ch;
    protected $header;
	protected $response;
	protected $info;
	
	public function __construct($options = array()) {
		$options = TXArray::mergeRecursive(array(
			'curlOptions' => array(
				CURLOPT_URL => $this->serviceUrl,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_POST => true,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_HEADER => true,
			),
		), $options);
        
        if (isset($options['curlOptions'][CURLOPT_POSTFIELDS]) && is_array($options['curlOptions'][CURLOPT_POSTFIELDS]))
            $options['curlOptions'][CURLOPT_POSTFIELDS] = http_build_query($options['curlOptions'][CURLOPT_POSTFIELDS]);
		
		$this->options = $options;
	}
	
	public function run() {
		$this->ch = curl_init();
		if (isset($this->options['curlOptions']))
			curl_setopt_array($this->ch, $this->options['curlOptions']);
		$this->response = curl_exec($this->ch);
		
        $this->response = explode("\r\n\r\n", $this->response, 2);
        if (count($this->response) == 1)
            $this->response = explode("\n\n", $this->response, 2);
        if (count($this->response) == 2) {
            $this->header = trim(array_shift($this->response));
            $this->response = trim(array_shift($this->response));
            
            $file = dirname(__FILE__) . '/request.log';
            $data = array(
                'time' => time(),
                'responseHeader' => $this->header,
                'responseBody' => $this->response,
            );
            
            if (isset($this->options['curlOptions'][CURLOPT_POSTFIELDS]))
                $data['postFields'] = $this->options['curlOptions'][CURLOPT_POSTFIELDS];
            
            if (isset($_SESSION))
                $data['session'] = $_SESSION;

            file_put_contents($file, json_encode($data) . "\n", FILE_APPEND);
        } else
            $this->response = false;
        
		$this->parse();
		
		return ($this->response === false || ($this->response instanceof SimpleXMLElement && $this->response->getName() == 'erro')) ? false : true;
	}

	protected function parse() {
		if ($this->response === false) {
			$errno = curl_errno($this->ch);
			$error = curl_error($this->ch);
			throw new ErrorException($error . " ($errno)", $errno);
		} elseif (is_string($this->response)) {
			$this->info = curl_getinfo($this->ch);
            if ($this->info['http_code'] != 200)
                throw new ErrorException("HTTP Response Error ({$this->info['http_code']})", $this->info['http_code']);
            
            $xml = simplexml_load_string($this->response);
            if ($xml->getName() == 'erro')
                throw new ErrorException('Service error: ' . ((string) $xml->mensagem) . ' (' . ((string) $xml->codigo) . ')', (string) $xml->codigo);

            $this->response = $xml;
		}
	}
	
	public function getResponse() {
		return $this->response;
	}
    
    public function getHeader() {
        return $this->header;
    }
	
	public function getInfo() {
		return $this->info;
	}
	
	public function getContentType() {
		
	}
	
}
